import axios from "axios"
import { Modal } from "antd"
import Loading from "../components/Loading"
import storage from "./storage"
//组件外使用router编程式导航的方法
import { createBrowserHistory } from "history"
let history = createBrowserHistory()

let http = axios.create({
    baseURL: '/api',
    timeout: 5000,
    withCredentials: true
})


//请求拦截器

http.interceptors.request.use(config => {
    let token = storage.get('wf-token')
    if (token) {
        config.headers['authorization'] = token;
    }
    return config
})

//响应拦截

http.interceptors.response.use(config => {
    //判断后台返回的状态
    let { state, code } = config.data;
    if (!state) {
        Modal.error({
            title: "错误提示",
            content: config.data.msg,
            centered: true
        })
    }
    //关闭加载动画

    Loading({ visible: false })

    //如果状态码是10022和1004 说明登入过期 要重新跳转到登入页
    if (code === "10022" || code === "1004") {
        window.location.reload()
        storage.rm('wf-token')
        history.push('/login')
    }

    return config
})

export default http